<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('请求列表')" />
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="formId">
                <div class="select-list">
                    <ul>
                        <li>
                            <label>名称：</label>
                            <input type="text" name="reqName"/>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="system:request:add">
                <i class="fa fa-plus"></i> 添加
            </a>
            <a class="btn btn-success" onclick="addByFav()" shiro:hasPermission="system:request:add">
                <i class="fa fa-plus"></i> 收藏夹添加
            </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
            <!-- data-auto-refresh设置true为启用自动刷新插件
			         data-auto-refresh-interval为每次自动刷新发生的时间（以秒为单位）默认60。
				     data-auto-refresh-silent设置为true可以自动无提示刷新。默认： true
				     data-auto-refresh-status 设置true为启用自动刷新。这是表加载时自动刷新的状态。单击按钮切换此属性。这只是自动刷新的默认状态，因为用户始终可以通过单击按钮来更改它。 默认： true  -->
            <table id="bootstrap-table" data-auto-refresh="true" data-auto-refresh-interval="10"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: bootstrap-table-auto-refresh-js" />
<script th:inline="javascript">
    var editFlag = [[${@permission.hasPermi('system:request:edit')}]];
    var listFlag = [[${@permission.hasPermi('system:request:list')}]];
    var removeFlag = [[${@permission.hasPermi('system:request:remove')}]];
    var approveFlag = [[${@permission.hasPermi('system:audit:view')}]];
    var requestStatusDatas = [[${@dict.getType('sys_request_status')}]];
    var prefix = ctx + "system/request2";

    $(function() {
        var options = {
            url: prefix + "/list",
            viewUrl2: prefix + "/samview/{id}",
            viewUrl3: prefix + "/serview/{id}",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            cancelUrl: prefix + "/cancel",
            exportUrl: prefix + "/export",
            modalName: "请求",
            sortName: "createTime",
            sortOrder: "desc",
            showRefresh: false,
            showToggle: false,
            showColumns: true,
            onLoadSuccess: function (data){
                onLoadSuccess(data);
            },
            columns: [
                {
                    field: 'reqId',
                    title: '主键',
                    visible: false
                },
                {
                    field: 'reqName',
                    title: '名称'
                },
                {
                    field: 'reqStatus',
                    title: '状态',
                    formatter: function(value, row, index) {
                        return $.table.selectDictLabel(requestStatusDatas, value);
                    }
                },
                {
                    field: 'samples',
                    title: '样品',
                    formatter: function (value, item, index) {
                        var samples = [];
                        $.each(value,function (index, data) {
                            var s = JSON.stringify(data);
                            var parse = JSON.parse(s);
                            if(parse.priority == 1){
                                //优先
                                samples.push('<a href="javascript:;" onclick="$.operate.view2(\''+parse.samId+'\',\'样品\')"><i class="fa fa-flask"></i><span class="sam-'+parse.samId +'"> '+parse.samName+' </span><i class="fa fa-flash" style="color: brown"></i></a><br>')
                            }else {
                                samples.push('<a href="javascript:;" onclick="$.operate.view2(\''+parse.samId+'\',\'样品\')"><i class="fa fa-flask"></i> <span class="sam-'+parse.samId +'">'+parse.samName+'</span></a><br>')
                            }
                        })
                        return samples.join('');
                    }
                },
                {
                    field: 'services',
                    title: '服务',
                    formatter: function (value, item, index) {
                        var services = [];
                        $.each(value,function (index, data) {
                            var s = JSON.stringify(data);
                            var parse = JSON.parse(s);
                            services.push('<a id="serv'+parse.infId+'" href="javascript:;" onclick="$.operate.view3(\''+parse.infId+'\',\'服务\')"><i class="fa fa-adjust fa-lg"></i><span class="sam-'+parse.sample.samId +'"> '+parse.serName+'</span></a><br>')
                        })
                        return services.join(' ');
                    }
                },
                {
                    field: 'reqDes',
                    title: '描述',
                    formatter: function(value, row, index) {
                        if(row.documents == null || row.documents.length == 0){
                            return '<span title="' + value + '">' + truncate(value, 30) + '</span>';
                        }
                        return '<span title="' + value + '">' + truncate(value, 30) +
                            '  <a href="javascript:void(0)" title="查看文档" onclick="showDocument(\'' + row.reqId + '\')">' +
                            '<i class="fa fa-paperclip"></i></a></span>';
                    }
                },
                {
                    field: 'project.proName',
                    title: '项目'
                },
                {
                    field: 'createTime',
                    title: '创建时间',
                    sortable: true
                },
                {
                    field: 'comment',
                    title: '审核意见',
                    visible: false
                },
                {
                    field: 'documents',
                    title: '文档',
                    visible: false,
                    formatter: function(value, row, index) {
                        if(value == null || value.length == 0){
                            return '<a href="javascript:void(0)"> - </a>';
                        }
                        return '<a href="javascript:void(0)" title="查看文档" onclick="showDocument(\'' + row.reqId + '\')"><i class="fa fa-search"></i></a>';
                    }
                },
                {
                    title: '操作',
                    // align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        var edit = '<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.editTab(\'' + row.reqId + '\')"><i class="fa fa-edit"></i> 编辑</a> ';
                        var submit = '<a class="btn btn-primary btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="save(\'' + row.reqId + '\')"><i class="fa fa-save"></i> 提交</a> ';
                        var services = '<a class="btn btn-info btn-xs ' + listFlag + '" href="javascript:void(0)" onclick="detail(\'' + row.reqId + '\')"><i class="fa fa-list"></i> 服务</a> ';
                        var remove = '<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.reqId + '\')"><i class="fa fa-remove"></i> 删除</a>';
                        var cancel = '<a class="btn btn-warning btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.cancel(\'' + row.reqId + '\')"><i class="fa fa-remove"></i> 取消</a>';
                        var stop = '<a class="btn btn-danger btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="stop(\'' + row.reqId + '\')"><i class="fa fa-stop"></i> 停止</a>';
                        var svapprove = '<a class="btn btn-primary btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="approve(\'' + row.reqId + '\')"><i class="fa fa-check"></i> 提交审核</a>';
                        var audit = '<a class="btn btn-primary btn-xs ' + approveFlag + '" href="javascript:void(0)" onclick="audit(\'' + row.reqId + '\')"><i class="fa fa-check"></i> Audit</a>';
                        var qaapprove = '<a class="btn btn-primary btn-xs ' + approveFlag + '" href="javascript:void(0)" onclick="qaapprove(\'' + row.reqId + '\')"><i class="fa fa-adjust"></i> 审核</a>';
                        var upload = '<a class="btn btn-info btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="upload(\'' + row.reqId + '\')"><i class="fa fa-upload"></i> 文档</a> ';

                        if(row.reqStatus == 1){       //edit
                            actions.push(edit);
                            actions.push(submit);
                            actions.push(remove);
                            actions.push(upload);
                        }else if(row.reqStatus == 13 || row.reqStatus == 6){  //Submit   / pending verification
                            actions.push(services);
                            actions.push(cancel);
                            actions.push(upload);
                        }else if(row.reqStatus == 14){  //Completed
                            actions.push(services);
                        }else if(row.reqStatus == 10 || row.reqStatus == 9){  //Error / notApproved
                            actions.push(services);
                            actions.push(remove);
                            actions.push(upload);
                        }else if(row.reqStatus == 4 || row.reqStatus == 11){  //cancelled / Reject
                            actions.push(services);
                            actions.push(svapprove);
                            actions.push(remove);
                            actions.push(upload);
                        } else  if (row.reqStatus == 7){ //pending QA approval
                            actions.push(services);
                            actions.push(audit);
                            actions.push(qaapprove);
                        }else {
                            actions.push(services);
                            actions.push(audit);
                            actions.push(upload);
                        }
                        return actions.join(' ');
                    }
                }]
        };
        $.table.init(options);

        // //每10秒自动刷新表格
        // setInterval(function () {
        //     $('#bootstrap-table').bootstrapTable('refresh');
        // }, 10000); // 10 秒
    });

    function onLoadSuccess(data){
        $.each(data.rows, function (index, value){
            if(value.length == 0){
                return;
            }
            var samIds = [];
            $.each(value.services, function( key, value, index) {
                if(value.process == 11){ //Done: 已完成
                    $(`#serv${value.infId} i:first-child`).css("color","green");
                    $(`#serv${value.infId} i:first-child`).removeClass();
                    $("#serv" + value.infId +" i:first-child").addClass("fa fa-check fa-lg")
                }else if(value.process == 12 || value.process == 1 ){ //Error、cancel: 出错
                    $("#serv" + value.infId +" i:first-child").css("color","red");
                    $("#serv" + value.infId +" i:first-child").removeClass();
                    $("#serv" + value.infId +" i:first-child").addClass("fa fa-close fa-lg")
                }else if(value.process == 2){   //Submitted: 提交等待
                    // $("#serv" + value.serviceId +" i:first-child").css("color","blue");
                    $("#serv" + value.infId +" i:first-child").removeClass();
                    $("#serv" + value.infId +" i:first-child").addClass("fa fa-hourglass-1 fa-lg")
                }else if(value.process == 3){   //Queued(下一个实验)
                    $("#serv" + value.infId +" i:first-child").removeClass();
                    $("#serv" + value.infId +" i:first-child").addClass("fa fa-hourglass-end fa-lg")
                }else if(value.process != null && value.process != 0){ //、temp、shim、...: 进行中
                    // $("#serv" + value.serviceId +" i:first-child").css("color","blue");
                    $("#serv" + value.infId +" i:first-child").removeClass();
                    $("#serv" + value.infId +" i:first-child").addClass("fa fa-spin fa-circle-o-notch fa-lg")
                }
                if(!samIds.includes(value.sample.samId)){
                    samIds.push(value.sample.samId);
                }
            });

            //随机颜色
            var clolrs = ["green", "blue", "red", "darkslategray", "olive", "purple", "navy", "darkorange"];
            for (let i = 0; i < samIds.length; i++) {
                $(".sam-"+samIds[i]).css("color", clolrs[i%8]);
            }
        });
    }

    /* 提交审核 */
    function qaapprove(reqId) {
        $.modal.open("QA验证", prefix + "/approveQA?reqId="+reqId, '770', '380');
    }

    function upload(reqId){
        $.modal.open("上传文档", prefix + "/uploadDoc?reqId="+reqId, '770', '680');
    }

    /*服务列表-详细*/
    function detail(reqId) {
        var url = prefix + '/services/' + reqId;
        $.modal.openTab("服务列表", url);
    }

    /*Audit列表*/
    function audit(reqId) {
        var url = prefix + '/audit/' + reqId;
        $.modal.openTab("Audit", url);
    }

    /* 提交审核 */
    function approve(reqId) {
        $.modal.confirm("确认重新提交审核吗？", function() {
            $.operate.post(prefix + "/approve", { "reqId": reqId});
        })
    }

    /* 提交 */
    function save(reqId) {
        $.modal.confirm("确认提交此申请吗？提交后不可修改以及删除", function() {
            $.operate.post(prefix + "/save", { "reqId": reqId});
        })
    }

    /* Document */
    function showDocument(reqId) {

        $.modal.open2("文档", prefix + "/showDocument?reqId="+reqId, ['关闭'], '770', '680');
    }

    function addByFav() {
        // TODO: 判断收藏夹是否有数据
        var flag = true;
        var config = {
            url: prefix + "/checkFav",
            type: "post",
            dataType: "json",
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
            },
            success: function(result) {
                //回调事件
                if(result.data == 0){
                    flag = false;
                }
                $.modal.closeLoading();
            }
        };
        $.ajax(config)
        if (flag){
            var url = prefix + '/addByFav';
            $.modal.open("通过收藏夹添加服务申请", url);
        }else {
            $.modal.alertError("收藏夹为空,请通过其它方式添加服务申请");
        }

    }

    // 工具函数：截断文字并添加省略号
    function truncate(str, maxLength) {
        return str.length > maxLength ? str.substring(0, maxLength) + '...' : str;
    }

</script>
</body>
</html>